package com.wyl.sso.service.Impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wyl.sso.dto.UserDto;
import com.wyl.sso.mapper.UserMapper;
import com.wyl.sso.model.UserDO;
import com.wyl.sso.service.UserService;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * @Auther: wyl
 * @Date: 2021/7/5
 * @Description:
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService {

     private final static String HASH_NAME="md5";
     private final static int HASH_TIMES=2;

    @Override
    public UserDto queryUserForLogin(String userName, String userPwd) {

        UserDO userDO = lambdaQuery().eq(UserDO::getLoginName, userName).one();

        if (userDO != null) {
            //取密码
            String pwd = userDO.getPassword();
            if (!StringUtils.hasText(pwd)) {
                return null;
            }
            //加盐
            ByteSource credentialsSalt = ByteSource.Util.bytes(userDO.getSalt());
            Object encodePwd = new SimpleHash(HASH_NAME, userPwd, credentialsSalt, HASH_TIMES);
            if(pwd.equals(encodePwd.toString())){
                UserDto userDto = new UserDto();
                BeanUtils.copyProperties(userDO,userDto);
                return userDto;
            }
        }
        return null;
    }
}
